package com.reggie.console.util;

import com.reggie.common.enums.ResponseCode;
import com.reggie.common.model.PageDTO;
import com.reggie.console.dto.ResultDTO;

import java.util.Collection;
import java.util.Collections;

/**
 * @author yth
 * @since 2023-06-11-1:44
 */
public class ResultBuilder {

    private ResultBuilder() {
    }

    private static final ResultDTO<?> EMPTY_POJO_RESULT = new EmptyResultDTO<>(null);

    private static final ResultDTO<?> EMPTY_COLLECTION_RESULT = new EmptyResultDTO<>(Collections.emptyList());

    private static final ResultDTO<?> EMPTY_PAGE_RESULT = new EmptyResultDTO<>(new PageDTO<>(Collections.emptyList(), 0, 1, 10));

    @SuppressWarnings("unchecked")
    public static <T> ResultDTO<T> emptyPojoResult() {
        return (ResultDTO<T>) EMPTY_POJO_RESULT;
    }

    @SuppressWarnings("unchecked")
    public static <T extends Collection<?>> ResultDTO<T> emptyCollectionResult() {
        return (ResultDTO<T>) EMPTY_COLLECTION_RESULT;
    }

    @SuppressWarnings("unchecked")
    public static <T extends PageDTO<?>> ResultDTO<T> emptyPageResult() {
        return (ResultDTO<T>) EMPTY_PAGE_RESULT;
    }

    /**
     * 不可修改
     */
    private static class EmptyResultDTO<T> extends ResultDTO<T> {

        public EmptyResultDTO(T content) {
            super.setCode(ResponseCode.OK.getCode());
            super.setMsg("");
            super.setData(content);
        }

    }

    /**
     * 得到正常结果的视图模型
     *
     * @param content 返回数据内容
     * @param <T>     数据类型
     * @param <E>     ResultVO子类
     * @return ResultDTO
     */
    @SuppressWarnings("unchecked")
    public static <T, E extends ResultDTO<T>> E ok(T content) {
        ResultDTO<T> result = new ResultDTO<>();
        result.setData(content);
        result.setCode(ResponseCode.OK.getCode());
        if (content instanceof String) {
            result.setMsg((String) content);
        }
        return (E) result;
    }

    /**
     * 得到异常结果的视图模型
     *
     * @param code 错误码
     * @param msg  消息
     * @param <T>  数据类型
     * @param <E>  ResultVO子类
     * @return ResultDTO
     */
    @SuppressWarnings("unchecked")
    public static <T, E extends ResultDTO<T>> E error(ResponseCode code, String msg) {
        ResultDTO<?> result = new ResultDTO<>();
        result.setCode(code.getCode());
        result.setMsg(msg);
        return (E) result;
    }

}
